# -*- coding:utf-8 -*- #
import threading

class CmdThread(threading.Thread):
    """overload Thread"""
    def __init__(self):
        super(CmdThread, self).__init__()
        self.is_terminal = False
        self.event = threading.Event()
        self._has_started = False
        self._is_alive = True

    def start(self, fun, param,
            data_filter, dispatcher, cycle_period):
        """prepare param and then use super.start
        
        fun= <function get_disk_space at 0xb7b72bc4>
        报警的阀值
        param= {'WarningData': 10}
        data_filter= <core.filters.MonitorFilter object at 0xb7b74aec>
        dispatcher <core.dispatcher.MonitorDispatcher object at 0xb7b7492c>
        检测的时间间隔
        cycle_period= 1
        
        """
        #worktype调用这个方法
        self.fun = fun
        self.param = param
        self.data_filter = data_filter
        self.dispatcher = dispatcher
        self.cycle_period = int(cycle_period)
        self.wait_time = self.cycle_period

        if not self._has_started:
            #执行run方法
            super(CmdThread, self).start()

            self._has_started = True
        else:
            self.notify()


    def run(self):
        """run until recycle or exit"""

        import socket
        while not self.is_terminal:
            try:
                #fun= <function get_disk_space at 0xb7b72bc4>
                #param= {'WarningData': 10}
                #执行数据采集脚本（插件）
                # plug_data = {'硬盘剩余': [2.4, "GB"],'硬盘使用率': [57.0, "%"]}
                plug_data = self.fun(self.param)
                #data_filter= <core.filters.MonitorFilter object at 0xb7b74aec>
                
                '''
                得到过滤数据
                filter_data = {'filter': 'monitor_filter', 
                '硬盘剩余': [2.4, "GB"],
                'datetime': 1333011170, 
                'type': 3, 
                'id': 21, 
                ''硬盘使用率': [57.0, "%"], 
                'is_attention': 0}
                如果是报警数据，不管级别
                'is_attention': 1
                '''
                filter_data = self.data_filter.filt(plug_data)
                print "filter_data == ",filter_data
                # dispatcher <core.dispatcher.MonitorDispatcher object at 0xb7b7492c>
                self.dispatcher.dispatch(filter_data)
            except socket.error:
                self.recycle()
            except:
                self.terminal()
                raise

            # 等待
            print "self.wait_time  =", self.wait_time
            self.event.wait(self.wait_time)

    def wait(self, period=None):
        self.wait_time = None

    def notify(self):
        print "go ddddddddddddddddd"
        self.wait_time = self.cycle_period
        self.event.set()
        while not self.event.isSet():
            self.event.set()
        self.event.clear()
        self._is_alive = True

    def recycle(self):
        self.event.clear()
        self.wait_time = None
        self._is_alive = False

    def is_alive(self):
        return self._is_alive and not self.is_terminal

    def terminal(self):
        self.is_terminal = True
        self._is_alive = False
        self.event.set()
